package cn.wolfcode.mq;

import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


/**
 * 订单创建的消费者监听, 会根据订单的成功/失败创建新的消息,给 webSocket 接收,
 * 如果失败还会给 MQOrderFailListener接收回补库存和修改本地标识
 * 使用OrderMQResult封装
 */
@Component
@RocketMQMessageListener(
        consumerGroup = "MQOrderCreateListener",
        topic = MQConstant.ORDER_PEDDING_TOPIC
)
@Slf4j
public class MQOrderCreateListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    @Transactional
    public void onMessage(OrderMessage orderMessage) {
        log.info("开始创建订单...");
        Long seckillId = orderMessage.getSeckillId();
        Integer time = orderMessage.getTime();
        String token = orderMessage.getToken();
        Long userPhone = orderMessage.getUserPhone();

        OrderMQResult orderMQResult = new OrderMQResult();
        BeanUtils.copyProperties(orderMessage,orderMQResult);

        // 发送新消息中的标签属性
        String tag = null;
        try {
            //int i =1 / 0;
            String orderNo = orderInfoService.doSeckill(seckillId, time, userPhone);
            orderMQResult.setOrderNo(orderNo);
            tag = MQConstant.ORDER_RESULT_SUCCESS_TAG;
            // 发送延迟消息, 用来15分钟后,确认订单支付状态,如果未支付,回补库存等操作
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC+":tag",
                    MessageBuilder.withPayload(orderNo).build(),5000,13);
        } catch (Exception e) {
            e.printStackTrace();
            tag = MQConstant.ORDER_RESULT_FAIL_TAG;
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
        }

        rocketMQTemplate.sendOneWay(MQConstant.ORDER_RESULT_TOPIC+":"+tag, JSON.toJSONString(orderMQResult));
    }
}
